import java.util.TreeMap;

/**
 * 731. 我的日程安排表 II
 * https://leetcode-cn.com/problems/my-calendar-ii/
 */
public class Solutions_731 {
    public static void main(String[] args) {
        MyCalendarTwo obj = new MyCalendarTwo();
        boolean res1 = obj.book(10, 20);  // output: true
        boolean res2 = obj.book(50, 60);  // output: true
        boolean res3 = obj.book(10, 40);  // output: true
        boolean res4 = obj.book(5, 15);  // output: false
        boolean res5 = obj.book(5, 10);  // output: true
        boolean res6 = obj.book(25, 55);  // output: true
    }
}

class MyCalendarTwo {
    TreeMap<Integer, Integer> treeMap = null;

    public MyCalendarTwo() {
        treeMap = new TreeMap<>();
    }

    public boolean book(int start, int end) {
        // 先行添加
        treeMap.put(start, treeMap.getOrDefault(start, 0) + 1);
        treeMap.put(end, treeMap.getOrDefault(end, 0) - 1);

        int count = 0;
        for (Integer v : treeMap.values()) {
            count += v;
            if (count >= 3) {
                // 还原
                treeMap.put(start, treeMap.getOrDefault(start, 0) - 1);
                treeMap.put(end, treeMap.getOrDefault(end, 0) + 1);
                return false;
            }
        }
        return true;
    }
}
